package org.jeecg.modules.xxgx.fpjf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.MinioUtil;
import org.jeecg.common.util.ValidatorUtils;
import org.jeecg.modules.common.util.AliSmsUtils;
import org.jeecg.modules.common.util.FreemarkerUtil;
import org.jeecg.modules.dxpz.entity.CsPtDxpz;
import org.jeecg.modules.dxpz.service.ICsPtDxpzService;
import org.jeecg.modules.jfptpz.entity.CsPtJfptpz;
import org.jeecg.modules.jfptpz.service.ICsPtJfptpzService;
import org.jeecg.modules.message.handle.impl.EmailSendMsgHandle;
import org.jeecg.modules.shorturl.entity.CsPtShorturl;
import org.jeecg.modules.shorturl.service.ICsPtShorturlService;
import org.jeecg.modules.sms.sms.enums.DxlxEnum;
import org.jeecg.modules.sms.sms.util.SmsUtil;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.util.ShortUrl;
import org.jeecg.modules.xxgx.common.enums.FpjflxEnum;
import org.jeecg.modules.xxgx.common.enums.FplxdmEnum;
import org.jeecg.modules.xxgx.common.util.BarCodeUtils;
import org.jeecg.modules.xxgx.fpgl.dto.YxjfMessageDto;
import org.jeecg.modules.xxgx.fpgl.entity.CsXxFpxx;
import org.jeecg.modules.xxgx.fpgl.service.ICsXxFpxxService;
import org.jeecg.modules.xxgx.fpht.util.DateUtil;
import org.jeecg.modules.xxgx.fpjf.entity.CsXxJfjl;
import org.jeecg.modules.xxgx.fpjf.mapper.CsXxJfjlMapper;
import org.jeecg.modules.xxgx.fpjf.param.FpjfSmsParam;
import org.jeecg.modules.xxgx.fpjf.param.FpjfYxParam;
import org.jeecg.modules.xxgx.fpjf.service.ICsXxJfjlService;
import org.jeecg.modules.xxgx.sjtb.service.ISjtbService;
import org.jeecg.modules.xxgx.sjtb.util.SjtbRequestUtil;
import org.jeecg.modules.xxgx.sjtb.vo.SjtbApiResponse;
import org.jeecg.modules.xxgx.sjtb.vo.SmsSendParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 销项发票交付记录
 * @Author: jeecg-boot
 * @Date:   2023-10-30
 * @Version: V1.0
 */
@Service
@Slf4j
public class CsXxJfjlServiceImpl extends ServiceImpl<CsXxJfjlMapper, CsXxJfjl> implements ICsXxJfjlService {

    @Autowired
    private ICsXxFpxxService csXxFpxxService;

    @Autowired
    private EmailSendMsgHandle emailSendMsgHandle;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private ICsPtShorturlService csPtShorturlService;

    @Autowired
    private AliSmsUtils aliSmsUtils;
    @Autowired
    private ISjtbService sjtbService;

    @Autowired
    private ICsPtJfptpzService csPtJfptpzService;
    @Autowired
    private ICsPtDxpzService csPtDxpzService;

    @Override
    public Result<String> yxjf(FpjfYxParam fpjfYxParam) {
        Result<String> result = new Result<>();
        CsXxFpxx csXxFpxx = csXxFpxxService.getById(fpjfYxParam.getFpxxid());
        if(csXxFpxx == null){
            return Result.error("发票信息不存在");
        }

        if(StringUtils.isEmpty(csXxFpxx.getKhlxyx()) && StringUtils.isEmpty(fpjfYxParam.getKhlxyx())) {
            return Result.error("客户联系邮箱为空！");
        }
        boolean isSuccess = true;
        String sbyy = "";
        try {
            YxjfMessageDto yxjfMessageDto = new YxjfMessageDto();
            BeanUtils.copyProperties(csXxFpxx, yxjfMessageDto);

            if(StringUtils.isBlank(csXxFpxx.getFpjfurl())) {
                //生成发票交付短链接地址
                String fpjfUrl = genFpjfShortUrl(csXxFpxx);
                csXxFpxx.setFpjfurl(fpjfUrl);
            }

            if(StringUtils.isNotBlank(csXxFpxx.getFpjfurl())) {
                String qrcodeBase64 = BarCodeUtils.getImage2Base64String(BarCodeUtils.generateBarcodeWithoutWhite(csXxFpxx.getFpjfurl(), null));

                yxjfMessageDto.setFpjfUrl(csXxFpxx.getFpjfurl());
                yxjfMessageDto.setFpjfEwmBase64(qrcodeBase64);
            }

            //获取minio前端访问地址
            if (StringUtils.isNotEmpty(csXxFpxx.getPdfdz()) && !csXxFpxx.getPdfdz().toLowerCase().startsWith("http")) {
                String fullUrl = MinioUtil.getObjectUrl(MinioUtil.getBucketName(), csXxFpxx.getPdfdz(), 7);
                yxjfMessageDto.setPdfdz(fullUrl);
            }
            if (StringUtils.isNotEmpty(csXxFpxx.getOfddz()) && !csXxFpxx.getOfddz().toLowerCase().startsWith("http")) {
                String fullUrl = MinioUtil.getObjectUrl(MinioUtil.getBucketName(), csXxFpxx.getOfddz(), 7);
                yxjfMessageDto.setOfddz(fullUrl);
            }
            if(FplxdmEnum.sdzp.getValue().equals(csXxFpxx.getFplxdm()) || FplxdmEnum.sdpp.getValue().equals(csXxFpxx.getFplxdm())) {
                if (org.parboiled.common.StringUtils.isNotEmpty(csXxFpxx.getXmldz()) && !csXxFpxx.getXmldz().toLowerCase().startsWith("http")) {
                    String fullUrl = MinioUtil.getObjectUrl(MinioUtil.getBucketName(), csXxFpxx.getXmldz(), 7);
                    yxjfMessageDto.setXmldz(fullUrl);
                }
            }

            String content = FreemarkerUtil.generteStringByFile("/org/jeecg/modules/xxgx/fpjf/ftl/yxjf.ftl", yxjfMessageDto);
            if(StringUtils.isEmpty(fpjfYxParam.getKhlxyx())) {
                sendYx(csXxFpxx, csXxFpxx.getKhlxyx(), content);
            } else {
                List<String> khlxyxList = new ArrayList<>();
                khlxyxList.add(fpjfYxParam.getKhlxyx());
                if(StringUtils.isNotEmpty(fpjfYxParam.getKhlxyx2())){
                    khlxyxList.add(fpjfYxParam.getKhlxyx2());
                }
                if(StringUtils.isNotEmpty(fpjfYxParam.getKhlxyx3())){
                    khlxyxList.add(fpjfYxParam.getKhlxyx3());
                }

                khlxyxList = khlxyxList.stream().distinct().collect(Collectors.toList());//去重
                for(String khlxyx : khlxyxList) {
                    sendYx(csXxFpxx, khlxyx, content);
                }
            }

            isSuccess = true;

        }catch (Exception e){
            isSuccess = false;
            sbyy = e.getMessage();
        } finally {

            if(isSuccess){
                return Result.OK("成功");
            } else {
                return Result.error(sbyy);
            }
        }
    }

    /**
     * 发送邮件
     * @param csXxFpxx
     * @param khlxyx
     * @param content
     */
    private void sendYx(CsXxFpxx csXxFpxx, String khlxyx, String content) {
        boolean isSuccess = true;
        String sbyy = "";
        try {
            emailSendMsgHandle.sendMsg(khlxyx, "发票交付", content);
        }catch (Exception e) {
            isSuccess = false;
            sbyy = e.getMessage();
        } finally {
            //保存邮箱交付记录
            CsXxJfjl csXxJfjl = new CsXxJfjl();
            csXxJfjl.setTenantId(csXxFpxx.getTenantId());
            csXxJfjl.setCompanyId(csXxFpxx.getCompanyId());
            csXxJfjl.setFormid(csXxFpxx.getId());
            csXxJfjl.setFpdm(csXxFpxx.getFpdm());
            csXxJfjl.setFphm(csXxFpxx.getFphm());
            csXxJfjl.setFphm(csXxFpxx.getFphm());
            csXxJfjl.setKhlxyx(khlxyx);
            csXxJfjl.setJflx(FpjflxEnum.EMAIL.getValue());
            csXxJfjl.setJfsj(DateUtil.now());
            csXxJfjl.setSfcg(isSuccess?"1":"0");
            csXxJfjl.setSbyy(sbyy);
            this.save(csXxJfjl);
        }
    }

    /**
     * 短信交付
     * @param fpjfSmsParam
     * @return
     */
    @Override
    public Result<String> dxjf(FpjfSmsParam fpjfSmsParam) {
        CsPtDxpz csPtDxpz = csPtDxpzService.getCurDxpz(TenantContext.getTenant(), DxlxEnum.FPJF.getValue());

        if(csPtDxpz == null) {
            return Result.error("未配置短信模板");
        }

        CsXxFpxx csXxFpxx = csXxFpxxService.getById(fpjfSmsParam.getFpxxid());
        if(csXxFpxx == null){
            return Result.error("发票信息不存在");
        }

        if(StringUtils.isEmpty(csXxFpxx.getKhlxfs()) && StringUtils.isEmpty(fpjfSmsParam.getKhlxfs())) {
            return Result.error("客户联系方式为空！");
        }
        boolean isSuccess = true;
        String sbyy = "";
        try {
            YxjfMessageDto yxjfMessageDto = new YxjfMessageDto();
            BeanUtils.copyProperties(csXxFpxx, yxjfMessageDto);

            if(StringUtils.isBlank(csXxFpxx.getFpjfurl())) {
                //生成发票交付短链接地址
                String fpjfUrl = genFpjfShortUrl(csXxFpxx);
                csXxFpxx.setFpjfurl(fpjfUrl);
            }

            if(StringUtils.isNotBlank(csXxFpxx.getFpjfurl())) {
                //String qrcodeBase64 = BarCodeUtils.getImage2Base64String(BarCodeUtils.generateBarcodeWithoutWhite(csXxFpxx.getFpjfurl(), null));

                yxjfMessageDto.setFpjfUrl(csXxFpxx.getFpjfurl());
                //yxjfMessageDto.setFpjfEwmBase64(qrcodeBase64);
            }

            String signName = csPtDxpz.getDxqm();
            String dxmp = csPtDxpz.getDxmp();
            if(StringUtils.isBlank(signName)){
                return Result.error("短信签名未配置");
            }
            if(StringUtils.isBlank(dxmp)){
                return Result.error("短信模板未配置");
            }
            String content = FreemarkerUtil.generteString(dxmp, yxjfMessageDto);
            content = "【" + signName + "】" + content;

            if(StringUtils.isEmpty(fpjfSmsParam.getKhlxfs())) {
                sendDx(yxjfMessageDto, csXxFpxx.getKhlxfs(), content);
            } else {
                List<String> khlxfsList = new ArrayList<>();
                khlxfsList.add(fpjfSmsParam.getKhlxfs());
                if(StringUtils.isNotEmpty(fpjfSmsParam.getKhlxfs2())){
                    khlxfsList.add(fpjfSmsParam.getKhlxfs2());
                }
                if(StringUtils.isNotEmpty(fpjfSmsParam.getKhlxfs3())) {
                    khlxfsList.add(fpjfSmsParam.getKhlxfs3());
                }

                khlxfsList = khlxfsList.stream().distinct().collect(Collectors.toList());//去重
                for(String khlxfs : khlxfsList) {
                    sendDx(yxjfMessageDto, khlxfs, content);
                }
            }

            isSuccess = true;

        }catch (Exception e) {
            isSuccess = false;
            sbyy = e.getMessage();
        } finally {

            if(isSuccess){
                return Result.OK("成功");
            } else {
                return Result.error(sbyy);
            }
        }
    }

    /**
     * 发送短信交付
     * @param yxjfMessageDto
     * @param khlxfs
     */
    private void sendDx(YxjfMessageDto yxjfMessageDto, String khlxfs, String content) {
        boolean isSuccess = true;
        String sbyy = "";
        String uid = "";
        try {
            if(StringUtils.isBlank(yxjfMessageDto.getFpjfUrl())){
                throw new JeecgBootException("交付URL未生成！");
            }
            //取配置信息
            CsPtJfptpz csPtJfptpz = csPtJfptpzService.getCurJfptpz(TenantContext.getTenant());
            if(csPtJfptpz == null){
                throw new JeecgBootException("未配置交付平台地址！");
            }

            if(!ValidatorUtils.isMobileNO(khlxfs)){
                isSuccess = false;
                sbyy = "非有效手机号码";
            } else {
                /*String signName = aliSmsUtils.getDictTextByKey("smsconfig", "signname");
                String templateCode = aliSmsUtils.getDictTextByKey("smsconfig", "fpjf_templateCode");
                JSONObject templateParamJson = new JSONObject();
                templateParamJson.put("fpjfUrl",yxjfMessageDto.getFpjfUrl());
                Result result = aliSmsUtils.sendSms(khlxfs, signName, templateCode, templateParamJson);
                if (result.isSuccess()) {
                    isSuccess = true;
                } else {
                    isSuccess = false;
                    sbyy = result.getMessage();
                }*/

                SmsSendParam smsSendParam = new SmsSendParam();
                uid = IdWorker.get32UUID();
                smsSendParam.setUid(uid);
                smsSendParam.setPhone(khlxfs);
                smsSendParam.setMsg(content);
                SjtbRequestUtil sjtbRequestUtil = new SjtbRequestUtil();
                sjtbRequestUtil.setServerUrl(csPtJfptpz.getServerUrl());
                sjtbRequestUtil.setAppKey(csPtJfptpz.getAppkey());
                sjtbRequestUtil.setAppSecret(csPtJfptpz.getAppsecret());
                SjtbApiResponse response = sjtbRequestUtil.request("/api/sms/send", JSONObject.toJSONString(smsSendParam));
                if(response.isSuccess()) {
                    isSuccess = true;
                } else {
                    isSuccess = false;
                    sbyy = response.getMessage();
                }
            }
        }catch (Exception e) {
            isSuccess = false;
            sbyy = e.getMessage();
        } finally {
            //保存短信交付记录
            CsXxJfjl csXxJfjl = new CsXxJfjl();
            csXxJfjl.setTenantId(yxjfMessageDto.getTenantId());
            csXxJfjl.setCompanyId(yxjfMessageDto.getCompanyId());
            csXxJfjl.setFormid(yxjfMessageDto.getId());
            csXxJfjl.setFpdm(yxjfMessageDto.getFpdm());
            csXxJfjl.setFphm(yxjfMessageDto.getFphm());
            csXxJfjl.setFphm(yxjfMessageDto.getFphm());
            csXxJfjl.setKhlxfs(khlxfs);
            csXxJfjl.setJflx(FpjflxEnum.DXJF.getValue());
            csXxJfjl.setJfsj(DateUtil.now());
            csXxJfjl.setSfcg(isSuccess?"1":"0");
            csXxJfjl.setSbyy(sbyy);
            csXxJfjl.setUid(uid);
            csXxJfjl.setDxnr(content);
            csXxJfjl.setJfts(SmsUtil.getDxts(content));
            this.save(csXxJfjl);
        }
    }

    /**
     * 生成短链接
     * @param csXxFpxx
     * @return
     */
    public String genFpjfShortUrl(CsXxFpxx csXxFpxx) {
        if(StringUtils.isEmpty(csXxFpxx.getFpjfurl())){
            //为空时上传一次，
            Result<String> result = sjtbService.pushFpxx(csXxFpxx.getId());
            if(result.isSuccess()) {
                return result.getResult();
            }
        }
        return this.genFpjfShortUrlPT(csXxFpxx);
    }

    @Override
    public String genFpjfShortUrlPT(CsXxFpxx csXxFpxx) {
        String fpjfUrl = "";
        String xxfpjf_ewm_url_prix = sysDictService.queryDictTextByKey("xxparams", "xxfpjf_ewm_url_prix");
        String shorturl_prix = sysDictService.queryDictTextByKey("xxparams", "shorturl_prix");
        if (StringUtils.isNotEmpty(xxfpjf_ewm_url_prix) && StringUtils.isNotEmpty(shorturl_prix)) {
            String url = xxfpjf_ewm_url_prix + "?id=" + csXxFpxx.getId() + "&tenantId=" + csXxFpxx.getTenantId() + "#/pages/tax/xxgx/fpjf/";

            CsPtShorturl csPtShorturl = new CsPtShorturl();
            long id = IdWorker.getId();
            csPtShorturl.setId(String.valueOf(id));
            csPtShorturl.setUrl(url);
            csPtShorturl.setCreateTime(DateUtil.now());
            csPtShorturl.setClicks(0);

            csPtShorturlService.save(csPtShorturl);

            fpjfUrl = shorturl_prix + (shorturl_prix.endsWith("/") ? "" : "/") + ShortUrl.base62Encode(id);

            //更新发票表发票交付地址
            CsXxFpxx updateFpjfurl = new CsXxFpxx();
            updateFpjfurl.setId(csXxFpxx.getId());
            updateFpjfurl.setFpjfurl(fpjfUrl);
            csXxFpxxService.updateById(updateFpjfurl);
        }

        return fpjfUrl;
    }
}
